package com.cinematicketscaning.app.dialog;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.*;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.DialogFragment;

public abstract class CenterDialogFragment<T extends ViewDataBinding> extends DialogFragment {
    private T binding;
    @Override
    public void onStart() {
        super.onStart();
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int adDialogWidth = (int) (dm.widthPixels * withRatio());

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//宽度全屏的关键
        if (isHeightFullScreen()) {
            getDialog().getWindow().setLayout(adDialogWidth, dm.heightPixels);
        } else {
            getDialog().getWindow().setLayout(adDialogWidth, getDialog().getWindow().getAttributes().height);
        }
        getDialog().getWindow().setGravity(Gravity.CENTER);
    }

    @Nullable
    @Override
    public final View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DataBindingUtil.inflate(inflater, setLayout(), container, false);
        return binding.getRoot();
    }

    @Override
    public final void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(binding);
    }

    /**
     * dialog宽度占屏幕宽度的比例
     * @return
     */
    protected float withRatio() {
        return 0.74f;
    }

    /**
     * 是否高度全屏
     * @return
     */
    protected boolean isHeightFullScreen() {
        return false;
    }

    protected abstract int setLayout();
    protected abstract void initView(T binding);
}
